Skip to content

Add ECoG encoding support, unified CLI, and end-to-end tests - #12

Open
aadhavthaniga wants to merge 9 commits into
GT-LIT-Lab:mainfrom
aadhavthaniga:tests/end-to-end
Open

aadhavthaniga wants to merge 9 commits into
GT-LIT-Lab:mainfrom
aadhavthaniga:tests/end-to-end

Conversation

@aadhavthaniga

@aadhavthaniga aadhavthaniga commented Oct 12, 2026 •

Copy link
Copy Markdown

This PR now has three parts, each building on the previous one: the end-to-end test suite and shared fixes, continuous ECoG encoding support, and ECoG support in the unified.py CLI. The fMRI CLI's effective defaults are unchanged.

1. End-to-end tests and shared fixes

Synthetic (tests/test_pipeline_synthetic.py, offline): plants a signal at FIR lags 2-3 in 10 vertices. It checks recovery, the lag-specific kernel, FDR selection, FIR causality, no held-out leakage, and determinism. It also checks downsampler and FIR outputs against independent reference implementations.

Golden (tests/test_golden_lebel.py, opt-in): pins train_simple.py's wordrate results on the LeBel UTS03 assembly. It skips unless LITCODER_LEBEL_ASSEMBLY points at the file. Tolerances come from measured CPU/MPS/cross-library variance (tests/fixtures/golden_lebel_uts03.json).

Folding and shared fixes:

  • encoding/models/folding.py:
    • Fold shuffling is now seeded; it previously used the unseeded global RNG.
    • Folding raises instead of silently falling back when there are too few samples or chunks, or when trimming empties a fold.
    • It validates trim_size and passes fold arguments by keyword.
  • NestedCVModel:
    • Normalizers are fit on training rows only.
    • Constant or non-finite targets get NaN scores and are excluded from summaries and FDR, while keeping their target identity.
    • Group labels propagate to the nested folds.
  • ActivationCache: cache keys cover the hook type and the stimuli, and a metadata mismatch raises.
  • AbstractTrainer refuses to truncate feature families with different row counts.
  • Results are saved before optional plotting and reporting, so a reporting failure can't lose a fitted run. This applies to both AbstractTrainer and UnifiedTrainer.
  • Saved results include versioned fold state, so predictions can be replayed with NestedCVModel.predict_fold.
  • NestedCVModel accepts supplied scikit-learn regressors and pipelines (encoding/models/estimator.py).
  • train_simple.py reads the assembly path from LITCODER_LEBEL_ASSEMBLY, falling back to the existing path.

Found along the way:

  • The non-legacy downsamplers (average, sum, last) misread split_indices and return about n_words rows. This is marked as a strict xfail.
  • NaN features are silently zeroed, while NaN targets pass through. A test documents this.

2. Continuous ECoG encoding

Assembly (encoding/assembly/ecog_processor.py): ECoGAssemblyGenerator reads a version-1 ecog.json manifest, or takes recording mappings directly. It validates:

  • a uniform neural grid at the declared sampling_rate_hz
  • declared time units and clocks, with an explicit affine synchronization required when the clocks differ
  • ordered electrode IDs, identical across pooled recordings
  • validity masks: valid_samples, optional unknown_samples, and invalid intervals that must agree with the masks
  • transcript onsets that fall inside each recording

Invalid rows and the original clocks are kept rather than dropped. It is also reachable through AssemblyGenerator.generate_assembly("ecog", …), which rejects fMRI-only arguments such as tr, volume and masks.

Feature alignment and temporal expansion (encoding/ecog_temporal.py):

  • Each extractor declares its own feature_specs method:
    • word methods (word_sum, word_mean, word_last) aggregate events into half-open neural bins;
    • rate methods (words_per_bin, words_per_second) give word counts per bin or per second;
    • speech_linear interpolates mapped speech frames, with a maximum gap.
  • Empty bins are zero.
  • Delays are given in seconds (delays_s) and rounded to sample offsets, with ties away from zero. Negative delays require retrospective=True.
  • Rows are expanded on the full original grid first. Rows that lack complete delayed feature support, sit on a recording edge, are invalid, or fall within declared neural-preprocessing support of an invalid row are then excluded, and every exclusion is recorded with its reason.
  • A configurable memory preflight (memory_budget_bytes) estimates the expanded design and the major ridge arrays before fitting.

Training: AbstractTrainer routes assemblies with modality == "ecog" to this preparation (fir_delays=None, downsampler=None, empty trimming, ecog_temporal_config), then fits the existing NestedCVModel. ECoG does not use fMRI TR downsampling, FIR expansion, trimming, or per-story z-scoring.

3. ECoG temporal cross-validation and safeguards

  • Protocols:
    • blocked: contiguous held-out blocks in recording/grid order.
    • recording: held-out recordings.
    • diagnostic_in_sample: one in-sample fit with one fixed positive ridge alpha. It is an engineering fit/replay check and emits no held-out metrics.
  • Purging: training rows whose recorded support overlaps an embargo-dilated held-out row in the same recording are removed in both the outer and inner folds. Purging uses the original time coordinates.
  • Validation of the temporal settings: unknown settings, legacy fold options (folding_type, chunk_length, groups), missing preprocessing support for held-out evaluation, fold counts or an embargo under the diagnostic protocol, and duplicate realized delays are all rejected.
  • Inference is not assessed. ECoG evaluation reports descriptive held-out Pearson correlations with inference_status="not_assessed". No p-values, FDR or significance masks are produced. Excluding dependencies does not establish independence between samples.
  • Saved metadata: results record the retained and excluded rows (recording, sample ID, time, validity), support bounds, the delays requested and realized, effective feature specs, provenance and the memory estimate.

4. ECoG in the unified.py CLI (new in this update)

python unified.py --dataset_type ecog --data_dir path/to/ecog_dir --subject S1 \
  --modalities wordrate embeddings --model_names wordrate word2vec \
  --vector_path vectors.bin --binary --ecog_config ecog_config.json \
  --cache_dir cache --n_outer_folds 5 --n_inner_folds 5 --alphas 0.1 1 10
  • --dataset_type ecog with --ecog_config (a JSON file holding the existing ecog_temporal_config) and --alphas.
  • The CLI reuses the existing pieces: the ECoG manifest loader, UnifiedTrainer.setup_models (unchanged) for extractors and the model, and AbstractTrainer's ECoG branch. There is no second CLI framework, and UnifiedTrainer is not modified.
  • fMRI-only options are rejected for ECoG with exit code 2: --tr, --ndelays, trimming, downsampling, --folding_type, --chunk_length, --story_idx, --story_order, --use_volume. --ecog_config and --alphas are rejected for fMRI.
  • fMRI defaults and the --tr/--ndelays/--lookback requirements are now applied after parsing. Effective fMRI configs are identical to the previous CLI (pinned by a snapshot test), and missing required options still exit with code 2.
  • Each run saves metadata["run_config"]: the effective CLI settings, the full temporal config, fit options, the encoding model, and SHA-256 hashes of the config and ecog.json. File names are stored rather than absolute paths.
  • The README has a short ECoG CLI example.

5. Regression testing and verification

New tests/test_unified_ecog_cli.py (23 tests, synthetic and offline):

  • CLI vs Python API parity: with identical deterministic inputs, these are exactly equal between the CLI and the API: correlations, predictions, outer and inner splits, weights, selected alphas, saved hyperparams and CV configuration, aligned rows, exclusions, support bounds and delay records.
  • Timing: sample times and IDs match the fixture, delays [0, 0.1, 0.2] s map to offsets [0, 1, 2], and declared gap rows are excluded.
  • Blocked CV: contiguous test blocks cover every row once, train and test don't overlap, the embargo removes training rows, and no retained training row overlaps the dilated held-out support.
  • Diagnostic protocol: CLI/API parity, plus rejection of fold counts and of a missing alpha.
  • No fMRI preparation: ECoG runs with the fMRI downsampling, FIR, structure_data and UnifiedTrainer preparation patched to fail.
  • Arguments: acceptance and rejection, and the fMRI main() still constructing UnifiedTrainer with the unchanged config.
  • Smoke: a subprocess run of unified.py on synthetic data with wandb disabled.

Verification on this branch: pytest tests gives 165 passed, 4 skipped, 3 xfailed. A manual synthetic CLI run exits 0 and saves results.

Known limitations and skipped tests

  • Skipped: the 4 golden LeBel tests, because LITCODER_LEBEL_ASSEMBLY was not set; that fixture is 2.8 GB. The golden path (train_simple.py through AbstractTrainer) is not changed by the CLI update.
  • Expected failures: 3 strict xfails for the non-legacy downsampler bug above.
  • Validation only on synthetic data. The tests show the encoding path is correct on synthetic recordings. Real-data alignment and diagnostic replay do not establish independent predictive performance or exact replication of the paper.
  • Not covered in ECoG: ECoG Lanczos, neural resampling and event-aligned analysis.
  • Untested CLI paths: the language-model and speech paths in the CLI are not tested end to end, because that would need model downloads; the CLI passes no tokenizer. They are covered at the API level with mocks.
  • ECoG --context_type: it has no effect when the manifest supplies precomputed stimuli.
  • Reproducibility hashes: the manifest hash covers ecog.json but not the .npy files it references.
  • Config errors surface late: diagnostic or temporal-config mistakes surface as a ValueError from the ECoG preparation step, not as argparse errors.
  • TensorBoard: the tensorboard logger backend needs tensorboard installed. Tests stub the loggers, and the subprocess smoke test uses wandb in disabled mode.

@aadhavthaniga
aadhavthaniga marked this pull request as ready for review October 13, 2026 22:38
@aadhavthaniga aadhavthaniga changed the title Add end-to-end tests for the encoding pipeline Add ECoG encoding support, unified CLI, and end-to-end tests Nov 19, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant